package com.scwatch.core.service.impl;

import com.scwatch.core.domain.Node;
import com.scwatch.core.domain.NodeAnchor;
import com.scwatch.core.repository.NodeAnchorDao;
import com.scwatch.core.service.NodeAnchorService;
import com.scwatch.core.service.NodeQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
public class NodeAnchorServiceImpl implements NodeAnchorService {



    private NodeAnchor findOrCreate(Node node, Node anchor) {
        NodeAnchor bean = nodeAnchorDao.findOne(new NodeAnchor.NodeAnchorId(node.getId(), anchor.getId()));
        if (bean == null) {
            bean = new NodeAnchor(node, anchor);
        }
        return bean;
    }

    @Transactional
    public void update(Node node, Integer[] anchorIds) {
        if (anchorIds == null) {
            return;
        }
        List<NodeAnchor> nodeAnchors = node.getNodeAnchors();
        nodeAnchors.clear();
        nodeAnchorDao.deleteByNodeId(node.getId());
        for (Integer id : anchorIds) {
            if(id!=null) {
                nodeAnchors.add(findOrCreate(node, nodeQueryService.get(id)));
            }

        }
    }

    private NodeQueryService nodeQueryService;

    @Autowired
    public void setNodeQueryService(NodeQueryService nodeQueryService) {
        this.nodeQueryService = nodeQueryService;
    }

    private NodeAnchorDao nodeAnchorDao;

    @Autowired
    public void setNodeAnchorDao(NodeAnchorDao nodeAnchorDao) {
        this.nodeAnchorDao = nodeAnchorDao;
    }

}
